# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         ssh_client.py
# Description:  ssh客户端
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/9/14 14:01
# -------------------------------------------------------------------------------
import re
import paramiko


class SshClient(object):
    """
    ssh客户端
    """

    def __init__(self, host, port, username, password):
        """
        初始化ssh客户端
        Args:
            host: 主机ip
            port: 端口
            username: 用户名
            password: 密码
        """
        self.host = host
        self.port = port or 22
        self.username = username
        self.password = password
        self.__transport = None
        self.ssh = None
        self.connect()

    def connect(self):
        """
        ssh连接主机
        Returns:

        """
        transport = paramiko.Transport(sock=(self.host, self.port))
        transport.connect(username=self.username, password=self.password)
        self.__transport = transport
        self.ssh = paramiko.SSHClient()
        self.ssh._transport = self.__transport

    def exec_command(self, command):
        """
        执行命令
        Args:
            command: 命令语句

        Returns:

        """
        stdin, stdout, stderr = self.ssh.exec_command(command=command)
        return [item[:-1] for item in stdout.readlines()]

    def close(self):
        """
        关闭连接
        Returns:

        """
        self.ssh.close()
        self.__transport.close()

    @property
    def disk_info(self):
        """
        查询磁盘信息
        Returns:

        """
        command = """
        df -h|sed 1d|awk '{print $1";"$2";"$3";"$4";"$5";"$6}'
        """
        results = self.exec_command(command)
        data = []
        title = ['文件系统', '容量', '已用', '可用', '已用%', '挂载点']
        for result in results:
            data.append(result.split(';'))
        return [dict(zip(title, item)) for item in data]

    @property
    def cpu_info(self):
        """
        查询CPU使用率
        Returns:

        """
        command = "vmstat 1 3|sed 1d|sed 1d|awk '{print $15}'"
        cpu = self.exec_command(command)
        pct = round((1 - (float(cpu[0]) + float(cpu[1]) + float(cpu[2])) / 3 / 100), 2)

        stdin, stdout, stderr = self.ssh.exec_command('cat /proc/cpuinfo')
        cpuinfo = re.findall(r'model name\t: (.*)', stdout.read().decode(encoding='utf-8'))

        return {'cpu': cpuinfo, 'pct': pct}

    @property
    def memory_info(self):
        """
        查询内存信息
        Returns:

        """
        command = 'cat /proc/meminfo'
        stdin, stdout, stderr = self.ssh.exec_command(command)
        str_out = stdout.read().decode(encoding='utf-8')
        total = re.search('MemTotal:(.*?)\n', str_out).group(1).lstrip().upper()
        total_num = re.search(r'\d+', total).group()

        free = re.search('MemFree:(.*?)\n', str_out).group(1).lstrip().upper()
        free_num = re.search(r'\d+', free).group()

        pct = round(float(free_num) / float(total_num), 2)

        return {'total': total, 'free': free, 'pct': pct}

    def kill_process(self, procsess_kw):
        """
        杀死进程
        Args:
            procsess_kw: 进程关键字

        Returns:

        """
        command = "ps -ef|grep " + procsess_kw + "|grep -v grep|awk '{print $2}'|xargs kill -9"
        self.ssh.exec_command(command=command)


if __name__ == '__main__':
    # ssh_client = SshClient('47.111.189.16', 22, 'appusr', 'ops1^8^')
    ssh_client = SshClient('192.168.0.35', 22, 'root', 'egenie1806')
    results = ssh_client.memory_info
    print(results)
    ssh_client.close()
